import axios from "axios";
import { METHOD } from "./config";
import { Toast } from "vant";
import {baseUrl} from "@/config";

let token = localStorage.getItem("token")
// console.log(token);
const instance = axios.create({
  baseURL: baseUrl,
  timeout: 5000,
  headers: {'authorization':'Bearer'+''+ token},
});

// let loading = null;
// 添加请求拦截器
instance.interceptors.request.use(
  function(config) {
    Toast.loading({
      message: "加载中...",
      forbidClick: true,
      loadingType: "spinner",
    });
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function(response) {
    Toast.clear()
    return response;
  },
  function(error) {
    Toast.clear()
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export function request(method, url, parmas) {
  switch (method) {
  case METHOD.GET:
    return GET(url, parmas);
  case METHOD.POST:
    return POST(url, parmas);
  case METHOD.PUT:
    return PUT(url, parmas)
  }
}

function GET(url, params) {
  return instance.get(url, params);
}

function POST(url, params) {
  return instance.post(url, params);
}
function PUT(url, params) {
  return instance.put(url, params);
}
